<template>
  <div class="container-box">
    <div class="table-wrap">
      <div class="filter-box">
        <el-form v-if="columns.filter(d => d.isFilter).length > 0" :inline="true" :model="query" class="demo-form-inline">
          <template v-for="(item) in columns.filter(d => d.isFilter)">
            <el-form-item :key="item.key" :label="item.title">
              <el-input v-model="query[item.key]" :placeholder="`请输入${item.title}`" />
            </el-form-item>
          </template>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="handleOp('add')">新增分类</el-button>
      </div>
      <div class="table-box">
        <el-table :data="list" :border="true" stripe header-row-class-name="table-header-row">
          <template v-for="(item, index) in columns.filter(d => d.isTable)">
            <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable">
              <template slot-scope="scope">
                <div v-if="item.key === ''" class="">{{ scope.row[item.key] }}</div>
                <div v-else class="">{{ handleRowResult(item, scope.row) }}</div>
              </template>
            </el-table-column>
          </template>
          <el-table-column label="操作" width="100px">
            <template slot-scope="scope">
              <el-row class="button-row">
                <el-button size="mini" type="primary" icon="el-icon-edit-outline" circle @click="handleOp('edit', scope.row)" />
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog :title="(dialogForm.id ? '编辑' : '新增') + '分类'" :visible.sync="dialogVisible">
      <el-form v-if="dialogColums.filter(d => d.isForm).length > 0" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="100px">
        <template v-for="(column, index) in dialogColums.filter(d => d.isForm)">
          <el-form-item v-if="column.key === 'store_id'" :key="index" :label="column.title" :prop="column.key">
            <el-select v-model="dialogForm[column.key]" :placeholder="`请选择${column.title}`" style="width: 100%;">
              <el-option v-for="item in list" :key="item.id" :label="item.store_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="column.title" :prop="column.key">
            <el-input v-model="dialogForm[column.key]" :type="column.type" :placeholder="`请输入${column.title}`" />
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <v-cate-from ref="cateFormRef" @callback="handleCateFromCb"></v-cate-from>
  </div>
</template>

<script>
import { goodsAddCate } from '../../api/goods'
import CateFrom from './cateForm.vue';
export default {
  name: 'GoodsCate',
  components: {
    vCateFrom: CateFrom
  },
  data() {
    var cateNameValidator = (rule, value, callback) => {
      value = value.trim();
      if (value === '') {
        callback(new Error('请输入分类名称'));
      } else {
        const item = this.list.find(d => d.cat_name === value);
        if (item) {
          callback(new Error('该分类名称已存在'));
        } else {
          callback();
        }
      }
    };
    return {
      columns: [
        { title: '商品分类', key: 'cat_name', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: true, isForm: true },
        { title: '更新时间', key: 'update_time', type: 'text', sortable: true, isFilter: false, isTable: true, isForm: false }
      ],
      query: {},
      saving: false,
      dialogVisible: false,
      dialogColums: [],
      rules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: ['change', 'blur'] },
          { required: true, validator: cateNameValidator }
        ]
      },
      dialogForm: {
        sort: 500
      },
      selCateId: '',
      selType: ''
    };
  },
  computed: {
    list() {
      const category = this.$store.getters.category;
      console.log('category==', category);
      return category?.data || [];
    },
    goodsCategoryDict() {
      return this.$store.getters.goodsCategoryDict;
    }
  },
  created() {
    console.log('cate==', this.goodsCategoryDict);
    this.getData();
    this.dialogColums = this.$json.cloneDeep(this.columns);
    console.log('dialogColums==', this.columns, this.dialogColums);
  },
  methods: {
    // 新增组件返回；
    handleCateFromCb(isFlag, result) {
      console.log('handleCateFromCb--', isFlag, result);
      if (isFlag) {
        this.getData();
      }
    },
    async getData() {
      // const { data } =
      await this.$store.dispatch('goods/getCategoryList')
      console.log('this.list==', this.list);
    },
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      if (item.key === 'stock') {
        if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
          const unitNum = row.stock % row.unit_convert2;
          const unitNum2 = Math.floor(row.stock / row.unit_convert2);
          return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        }
        return `${row.stock}${row.unit_name}`
      }
      return row[item.key] || '';
    },
    handleOp(type, row) {

      // if (type === 'add') {
      //   this.dialogVisible = true;
      //   this.dialogForm = {
      //     sort: 500
      //   }
      // }
      // else 
      // if (type === 'edit') {
      //   this.selCateId = row.cat_id;
      //   this.$refs.cateFormRef.showDialog('fetch');
      // }
      this.$refs.cateFormRef.showDialog(type, { id: row?.cat_id });
    },
    async onDialogConfirm() {
      let isValid = false; let msg = '';
      this.$refs.dialogForm.validate(valid => {
        console.log('valid==', valid);
        isValid = valid;
      })
      if (this.saving) msg = '请勿重复提交';
      if (!isValid) msg = '请检查提交内容';
      if (msg) {
        this.$message.error(msg)
        return;
      }
      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        const { data } = await goodsAddCate(payload);
        console.log('goodsAddCate==', data);
        if (data && data.length === 2) {
          if (data[1]) {
            this.getData();
            this.$message.success('添加成功')
            this.dialogVisible = false;
          } else {
            this.$message.error(`添加失败: ${payload.cat_name} 已存在`)
          }
        } else {
          this.$message.error(`异常：添加失败`)
        }
      } catch (e) {
        console.log('goodsAddCate--e==', e);
      }
      this.saving = false;
    }
  }
}

</script>
<style lang="scss" scoped>
</style>
